package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.model.dto.BindTeachplanMediaDto;
import com.xuecheng.content.model.dto.SaveTeachplanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.service.TeachplanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author cyf
 * @version 1.0
 * @description #TODO
 * @date 2024/8/29 21:41
 **/
@Slf4j
@Service
public class TeachplanServiceImpl implements TeachplanService {
    @Resource
    TeachplanMapper teachplanMapper;
    @Resource
    TeachplanMediaMapper teachplanMediaMapper;

    @Override
    public List<TeachplanDto> findTeachplanTree(Long courseId) {
        List<TeachplanDto> teachplanDtos = teachplanMapper.selectTreeNodes(courseId);
        return teachplanDtos;
    }

    @Override
    @Transactional
    public void saveTeachplan(SaveTeachplanDto teachplanDto) {
        //课程计划id
        Long id = teachplanDto.getId();
        //修改课程计划
        if (id != null) {
            Teachplan teachplan = teachplanMapper.selectById(id);
            BeanUtils.copyProperties(teachplanDto, teachplan);
            teachplanMapper.updateById(teachplan);
        } else {
            //取出同父同级别的课程计划数量
            int count = getTeachplanCount(teachplanDto.getCourseId(), teachplanDto.getParentid());
            Teachplan teachplanNew = new Teachplan();
            //设置排序号
            teachplanNew.setOrderby(count + 1);
            BeanUtils.copyProperties(teachplanDto, teachplanNew);
            teachplanMapper.insert(teachplanNew);
        }

    }

    @Override
    @Transactional
    public void deleteTeachplan(Long id) {
        Teachplan teachplan = teachplanMapper.selectById(id);
        int grade = teachplan.getGrade();
        //删除第一级别的章时要求章下边没有小节方可删除
        if (grade == 1) {
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getParentid, id);
            Integer count = teachplanMapper.selectCount(queryWrapper);
            if (count == 0) {
                teachplanMapper.deleteById(id);
            } else {
                XueChengPlusException.cast("120409", "课程计划信息还有子级信息，无法操作");
            }
        } else if (grade == 2) {
            teachplanMapper.deleteById(id);
            //删除第二级别的小节的同时需要将其它关联的视频信息也删除。
            LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TeachplanMedia::getTeachplanId, id);
            teachplanMediaMapper.delete(queryWrapper);
        }
    }

    @Override
    @Transactional
    public void moveTeachplan(String moveType, Long id) {
        Teachplan teachplanCur = teachplanMapper.selectById(id);
        Integer teachplanCurOrderby = teachplanCur.getOrderby();
        if (moveType.equals("moveup")) {
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getParentid, teachplanCur.getParentid());
            queryWrapper.eq(Teachplan::getCourseId, teachplanCur.getCourseId());
            queryWrapper.eq(Teachplan::getGrade, teachplanCur.getGrade());
            queryWrapper.lt(Teachplan::getOrderby, teachplanCurOrderby);
            queryWrapper.orderByDesc(Teachplan::getOrderby);
            queryWrapper.last("LIMIT 1");
            Teachplan teachplanPrev = teachplanMapper.selectOne(queryWrapper);
            if (teachplanPrev != null) {
                Integer teachplanPrevOrderby = teachplanPrev.getOrderby();
                teachplanCur.setOrderby(teachplanPrevOrderby);
                teachplanPrev.setOrderby(teachplanCurOrderby);
                teachplanMapper.updateById(teachplanPrev);
                teachplanMapper.updateById(teachplanCur);
            }
        } else if (moveType.equals("movedown")) {
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getParentid, teachplanCur.getParentid());
            queryWrapper.eq(Teachplan::getCourseId, teachplanCur.getCourseId());
            queryWrapper.eq(Teachplan::getGrade, teachplanCur.getGrade());
            queryWrapper.gt(Teachplan::getOrderby, teachplanCurOrderby);
            queryWrapper.orderByAsc(Teachplan::getOrderby);
            queryWrapper.last("LIMIT 1");
            Teachplan teachplanSucc = teachplanMapper.selectOne(queryWrapper);
            if (teachplanSucc != null) {
                Integer teachplanPrevOrderby = teachplanSucc.getOrderby();
                teachplanCur.setOrderby(teachplanPrevOrderby);
                teachplanSucc.setOrderby(teachplanCurOrderby);
                teachplanMapper.updateById(teachplanSucc);
                teachplanMapper.updateById(teachplanCur);
            }
        }
    }

    /**
     * 获取最新的排序号
     *
     * @param courseId 课程id
     * @param parentId 父课程计划id
     * @return int 最新排序号
     * @date 2024/9/1
     */
    private int getTeachplanCount(long courseId, long parentId) {
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId, courseId);
        queryWrapper.eq(Teachplan::getParentid, parentId);
        Integer count = teachplanMapper.selectCount(queryWrapper);
        return count;
    }

    /**
     * 绑定课程计划与媒资
     * @param bindTeachplanMediaDto
     * @return
     */
    @Transactional
    @Override
    public TeachplanMedia associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {
        //教学计划id
        Long teachplanId = bindTeachplanMediaDto.getTeachplanId();
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if(teachplan==null){
            XueChengPlusException.cast("教学计划不存在");
        }
        Integer grade = teachplan.getGrade();
        if(grade!=2){
            XueChengPlusException.cast("只允许第二级教学计划绑定媒资文件");
        }
        //课程id
        Long courseId = teachplan.getCourseId();

        //先删除原来该教学计划绑定的媒资
        teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId,teachplanId));

        //再添加教学计划与媒资的绑定关系
        TeachplanMedia teachplanMedia = new TeachplanMedia();
        teachplanMedia.setCourseId(courseId);
        teachplanMedia.setTeachplanId(teachplanId);
        teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());
        teachplanMedia.setMediaId(bindTeachplanMediaDto.getMediaId());
        teachplanMedia.setCreateDate(LocalDateTime.now());
        teachplanMediaMapper.insert(teachplanMedia);
        return teachplanMedia;
    }

    /**
     *
     * @param teachPlanId
     * @param mediaId
     */
    @Override
    public void deleteAssociationMedia(String teachPlanId, String mediaId) {
        teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId,teachPlanId).eq(TeachplanMedia::getMediaId,mediaId));
    }

}
